package com.example.demo.repository.base;

import com.example.demo.util.PageBean;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;

/**
 * Created by leohe on 2017/3/29.
 */

public class BaseRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseRepository<T, ID> {

    private final EntityManager entityManager;


    //父类没有不带参数的构造方法，这里手动构造父类
    public BaseRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {
        super(domainClass, entityManager);
        this.entityManager = entityManager;
    }

    //通过EntityManager来完成查询
    @SuppressWarnings("unchecked")
    @Override
    public List<Object[]> listBySQL(String sql) {
        return entityManager.createNativeQuery(sql).getResultList();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List listByPage(String sql, Class var2, PageBean pageBean){
        Query q = entityManager.createNativeQuery(sql, var2);
        q.setFirstResult((pageBean.getCurrentPageNum() - 1) * pageBean.getPerPageSize());
        q.setMaxResults(pageBean.getPerPageSize());
        return q.getResultList();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Object[]> listSQLByPage(String sql,PageBean pageBean){
        Query q = entityManager.createNativeQuery(sql);
        q.setFirstResult((pageBean.getCurrentPageNum() - 1) * pageBean.getPerPageSize());
        q.setMaxResults(pageBean.getPerPageSize());
        return q.getResultList();
    }

    @Override
    public int getTotalCount(String sql) {
        Object object = this.entityManager.createNativeQuery(sql).getSingleResult();
        if ( object == null ){
            return 0;
        }else {
            return ((BigInteger)object).intValue();
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Object> listByHQL(String sql) {
        Query q = entityManager.createQuery(sql);
        return q.getResultList();
    }

    @Override
    public void updateBySql(String sql, Object... args) {
        Query query = entityManager.createNativeQuery(sql);
        int i = 0;
        for (Object arg : args) {
            query.setParameter(++i, arg);
        }
        query.executeUpdate();
    }

    @Override
    public void updateByHql(String hql, Object... args) {
        Query query = entityManager.createQuery(hql);
        int i = 0;
        for (Object arg : args) {
            query.setParameter(++i, arg);
        }
        query.executeUpdate();
    }
}
